package com.houxm.jbapu;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

public class Tables {
	
	private Map<String, Object> tables = new HashMap<String, Object>();
	
	public static Tables o = new Tables();
	
	public void putTable(String tableName, Table t) {
		if(this.tables.containsKey(tableName)) {
			Object obj = this.tables.get(tableName);
			if(obj instanceof Table) {
				LinkedList<Table> linked = new LinkedList<Table>();
				linked.add((Table) obj);
				linked.add(t);
				this.tables.put(tableName, linked);
			}else {
				@SuppressWarnings("unchecked")
				LinkedList<Table> linked = (LinkedList<Table>) obj;
				linked.add(t);
			}
		}else {
			this.tables.put(tableName, t);
		}
	}
	
	public Table getTable(String name) {
		String dbName = null;
		String tableName = null;
		if(name.contains(".")) {
			String[] schem = name.split("\\.");
			if(schem.length!=2) {
				throw new JbapuRuntimeException("error tableName syntax!");
			}else {
				dbName = schem[0];
				tableName = schem[1];
			}
		}else {
			tableName = name;
		}
		Object obj = this.tables.get(tableName);
		if(obj!=null) {
			if(obj instanceof Table) {
				return (Table) obj;
			}else {
				@SuppressWarnings("unchecked")
				LinkedList<Table> linked = (LinkedList<Table>) obj;
				if(dbName==null || "".equals(dbName)) {
					String throwStr = "MySql has multiple table named "+tableName+" in different databases, they are as follows: ";
					for (Iterator<Table> iterator = linked.iterator(); iterator.hasNext();) {
						Table table = iterator.next();
						throwStr += table.getDbName()+" ";
					}
					throwStr += ", but dbName is blank here! you should use it like this: [dbName].[tableName]";
					throw new JbapuRuntimeException(throwStr);
				}else {
					
					for (Iterator<Table> iterator = linked.iterator(); iterator.hasNext();) {
						Table table = iterator.next();
						if(table.getDbName().equals(dbName)) {
							return table;
						}
					}
					return null;
				}
			}
		}else
			return null;
	}
	
	public static void main(String[] args) {
		String name = "sss.sss1";
		System.out.println(name.contains("."));
		System.out.println(name.split("\\.").length);
		System.out.println(name.split("\\.")[0]);
		System.out.println(name.split("\\.")[1]);
	}
}
